<template>
  <!-- 供应商响应分析 -->
  <div class="SupplierResponse">
    <div class="titleBar">
      <div class="title">
        供应商响应分析
        <div class="dateRange">
          <a-range-picker
            v-model:value="dateRange"
            size="small"
            :allowClear="false"
            value-format="YYYY-MM-DD"
            format="YYYY-MM-DD"
            style="margin-right: 8px"
          />
          <a-button
            size="small"
            type="primary"
            class="queryBtn"
            @click="outageDashboardData"
            >查询</a-button
          >
          <a-button size="small" type="link" @click="handleReset"
            >重置</a-button
          >
        </div>
      </div>
    </div>
    <div class="content">
      <div class="leftChart">
        <div class="chartTitle">各厂商MTTR数据对比</div>
        <a-spin :spinning="loading1">
          <div ref="leftChartRef1" class="chartContainer"></div>
        </a-spin>
        <div class="tips">
          MTTR(Mean Time To
          Repair)，平均修复时间，数值等于故障总时长/总故障次数。
        </div>
      </div>
      <div class="rightChart">
        <div class="chartTitle">
          {{ leftChartRefTitle1 }}-各电站MTTR数据对比
        </div>
        <a-spin :spinning="loading1">
          <div
            ref="rightChartRef1"
            class="chartContainer chartContainer1"
          ></div>
        </a-spin>
      </div>
    </div>
    <div class="content">
      <div class="leftChart">
        <div class="chartTitle">各厂商MTBF数据对比</div>
        <a-spin :spinning="loading2">
          <div ref="leftChartRef2" class="chartContainer"></div>
        </a-spin>
        <div class="tips">
          MTBF (Mean Time Between Failures)
          ,平均故障间隔时间，数值等于总运行时长/总故障次数。
        </div>
      </div>
      <div class="rightChart">
        <div class="chartTitle">
          {{ leftChartRefTitle2 }}-各电站MTBF数据对比
        </div>
        <a-spin :spinning="loading2">
          <div
            ref="rightChartRef2"
            class="chartContainer chartContainer1"
          ></div>
        </a-spin>
      </div>
    </div>
  </div>
</template>

<script setup>

import * as echarts from "echarts";
import dayjs from "dayjs";
const getDefaultDateRange = () => {
  // 默认选上月的1号到上月的最后一天
  const end = dayjs().subtract(1, "month").endOf("month");
  const start = dayjs().subtract(1, "month").startOf("month");
  return [start.format("YYYY-MM-DD"), end.format("YYYY-MM-DD")];
};
const dateRange = ref(getDefaultDateRange());
const $api = inject("$api");

const leftChartRef1 = ref(null);
const rightChartRef1 = ref(null);
const leftChartRef2 = ref(null);
const rightChartRef2 = ref(null);
const leftChartRefTitle1 = ref("所有厂商");
const leftChartRefTitle2 = ref("所有厂商");
let leftChart1 = null;
let rightChart1 = null;
let leftChart2 = null;
let rightChart2 = null;
const selectedBarIndex1 = ref(-1);
const selectedBarIndex2 = ref(-1);
const loading1 = ref(false);
const loading2 = ref(false);
const mttrChartData = ref({}); // MTTR独立数据
const mtbfChartData = ref({}); // MTBF独立数据

const initLeftChart1 = () => {
  if (!leftChartRef1.value) return;

  if (leftChart1) {
    leftChart1.dispose();
  }

  const mttrData =
    mttrChartData.value?.faultDealBrandResponseMttrAnalyzeDtoList || [];
  const supplierNames = mttrData.map((item) => item.supplierName);
  let values = mttrData.map((item) => item.mttrValue);
  const maxValue = Math.max(...values);

  leftChart1 = echarts.init(leftChartRef1.value);
  // 检查数据是否存在
  if (mttrData.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    leftChart1.setOption(option);
    // 数据为空时，同时清空右侧图表
    initRightChart1();
    return;
  }
  const defaultColor = new echarts.graphic.LinearGradient(0, 0, 1, 0, [
    { offset: 0, color: "#00E5FF" },
    { offset: 1, color: "#0077FF" },
  ]);
  const highlightColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: "#FF9F43" },
    { offset: 1, color: "#FF7A00" },
  ]);
  const seriesData = values.map((value) => ({
    value,
    itemStyle: {
      color: defaultColor,
      borderRadius: 8,
    },
  }));
  const option = {
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "3%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
    xAxis: {
      type: "value",
      max: maxValue,
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dashed",
        },
      },
    },
    yAxis: {
      type: "category",
      data: supplierNames,
      inverse: true,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        margin: 10,
      },
    },
    series: [
      {
        type: "bar",
        data: seriesData,
        barWidth: 12,
        itemStyle: {
          color: defaultColor,
          borderRadius: 8,
        },
        showBackground: true,
        backgroundStyle: {
          color: "rgba(51, 65, 85, 0.4)",
          borderRadius: 8,
        },
      },
    ],
  };

  leftChart1.setOption(option);
  leftChart1.on("click", function (params) {
    if (params.componentType === "series" && params.seriesType === "bar") {
      const stationName = params.name;
      const clickedDataIndex = params.dataIndex;
      const currentOption = leftChart1.getOption();
      const currentSeriesData = currentOption.series[0].data;
      leftChartRefTitle1.value = stationName;
      if (selectedBarIndex1.value === clickedDataIndex) {
        currentSeriesData[clickedDataIndex].itemStyle.color = defaultColor;
        leftChartRefTitle1.value = "所有厂商";
        selectedBarIndex1.value = -1;
        initRightChart1(); // 重新初始化右侧图表显示所有数据
      } else {
        currentSeriesData.forEach((item, index) => {
          if (index === clickedDataIndex) {
            item.itemStyle.color = highlightColor;
          } else {
            item.itemStyle.color = defaultColor;
          }
        });
        selectedBarIndex1.value = clickedDataIndex;
        initRightChart1(stationName); // 初始化右侧图表显示选中厂商数据
      }
      leftChart1.setOption({
        series: [
          {
            data: currentSeriesData,
          },
        ],
      });
    }
  });
};

const initRightChart1 = (selectedSupplier = null) => {
  if (!rightChartRef1.value) return;

  if (rightChart1) {
    rightChart1.dispose();
  }

  rightChart1 = echarts.init(rightChartRef1.value);

  const mttrData =
    mttrChartData.value?.faultDealBrandResponseMttrAnalyzeDtoList || [];
  let stationNames = [];
  let values = [];

  // 检查数据是否存在
  if (mttrData.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    rightChart1.setOption(option);
    return;
  }

  if (selectedSupplier) {
    // 显示选中厂商的电站数据
    const supplierData = mttrData.find(
      (item) => item.supplierName === selectedSupplier
    );
    if (supplierData && supplierData.stationMttrMap) {
      const stationMttrArray = Object.entries(supplierData.stationMttrMap);
      // 按MTTR值从小到大排列
      stationMttrArray.sort((a, b) => a[1] - b[1]);
      stationNames = stationMttrArray.map((item) => item[0]);
      values = stationMttrArray.map((item) => item[1]);
    }
  } else {
    // 显示所有厂商的所有电站数据
    const allStationMaps = mttrData.reduce((acc, item) => {
      if (item.stationMttrMap) {
        return { ...acc, ...item.stationMttrMap };
      }
      return acc;
    }, {});
    const allStationArray = Object.entries(allStationMaps);
    // 按MTTR值从小到大排列
    allStationArray.sort((a, b) => a[1] - b[1]);
    stationNames = allStationArray.map((item) => item[0]);
    values = allStationArray.map((item) => item[1]);
  }

  // 如果没有数据，显示暂无数据
  if (stationNames.length === 0 || values.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    rightChart1.setOption(option);
    return;
  }

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "0",
      top: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: stationNames,
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        show: false,
        alignWithLabel: true,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        interval: 0,
        rotate: 45,
      },
    },
    yAxis: {
      type: "value",
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      splitNumber: 4,
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dashed",
        },
      },
    },
    series: [
      {
        type: "bar",
        barWidth: 16,
        data: values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "#00E5FF" },
            { offset: 1, color: "#0077FF" },
          ]),
          borderRadius: [8, 8, 0, 0],
        },
        showBackground: true,
        backgroundStyle: {
          color: "rgba(51, 65, 85, 0.4)",
          borderRadius: [8, 8, 0, 0],
        },
      },
    ],
  };

  rightChart1.setOption(option);
};

const initLeftChart2 = () => {
  if (!leftChartRef2.value) return;

  if (leftChart2) {
    leftChart2.dispose();
  }

  // 使用MTBF独立数据
  const mtbfData =
    mtbfChartData.value?.faultDealBrandResponseMtbfAnalyzeDtoList || [];
  const supplierNames = mtbfData.map((item) => item.supplierName);
  const values = mtbfData.map((item) => item.mtbfValue);
  const maxValue = Math.max(...values);

  leftChart2 = echarts.init(leftChartRef2.value);
  // 检查数据是否存在
  if (mtbfData.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    leftChart2.setOption(option);
    // 数据为空时，同时清空右侧图表
    initRightChart2();
    return;
  }
  const defaultColor = new echarts.graphic.LinearGradient(0, 0, 1, 0, [
    { offset: 0, color: "rgb(17, 168, 219)" },
    { offset: 1, color: "rgb(56, 229, 165)" },
  ]);
  const highlightColor = new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    { offset: 0, color: "#FF9F43" },
    { offset: 1, color: "#FF7A00" },
  ]);
  const seriesData = values.map((value) => ({
    value,
    itemStyle: {
      color: defaultColor,
      borderRadius: 8,
    },
  }));
  const option = {
    grid: {
      left: "3%",
      right: "4%",
      bottom: "3%",
      top: "3%",
      containLabel: true,
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
    xAxis: {
      type: "value",
      max: maxValue,
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dashed",
        },
      },
    },
    yAxis: {
      type: "category",
      data: supplierNames,
      inverse: true,
      axisLine: {
        show: false,
      },
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        margin: 10,
      },
    },
    series: [
      {
        type: "bar",
        data: seriesData,
        barWidth: 12,
        itemStyle: {
          color: defaultColor,
          borderRadius: 8,
        },
        showBackground: true,
        backgroundStyle: {
          color: "rgba(51, 65, 85, 0.4)",
          borderRadius: 8,
        },
      },
    ],
  };

  leftChart2.setOption(option);
  leftChart2.on("click", function (params) {
    if (params.componentType === "series" && params.seriesType === "bar") {
      const stationName = params.name;
      const clickedDataIndex = params.dataIndex;
      const currentOption = leftChart2.getOption();
      const currentSeriesData = currentOption.series[0].data;
      leftChartRefTitle2.value = stationName;
      if (selectedBarIndex2.value === clickedDataIndex) {
        currentSeriesData[clickedDataIndex].itemStyle.color = defaultColor;
        leftChartRefTitle2.value = "所有厂商";
        selectedBarIndex2.value = -1;
        initRightChart2(); // 重新初始化右侧图表显示所有数据
      } else {
        currentSeriesData.forEach((item, index) => {
          if (index === clickedDataIndex) {
            item.itemStyle.color = highlightColor;
          } else {
            item.itemStyle.color = defaultColor;
          }
        });
        selectedBarIndex2.value = clickedDataIndex;
        initRightChart2(stationName); // 初始化右侧图表显示选中厂商数据
      }
      leftChart2.setOption({
        series: [
          {
            data: currentSeriesData,
          },
        ],
      });
    }
  });
};

const initRightChart2 = (selectedSupplier = null) => {
  if (!rightChartRef2.value) return;

  if (rightChart2) {
    rightChart2.dispose();
  }

  rightChart2 = echarts.init(rightChartRef2.value);

  const mtbfData =
    mtbfChartData.value?.faultDealBrandResponseMtbfAnalyzeDtoList || [];
  let stationNames = [];
  let values = [];

  // 检查数据是否存在
  if (mtbfData.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    rightChart2.setOption(option);
    return;
  }

  if (selectedSupplier) {
    // 显示选中厂商的电站数据
    const supplierData = mtbfData.find(
      (item) => item.supplierName === selectedSupplier
    );
    if (supplierData && supplierData.stationMtbfMap) {
      const stationMtbfArray = Object.entries(supplierData.stationMtbfMap);
      // 按MTBF值从大到小排列
      stationMtbfArray.sort((a, b) => b[1] - a[1]);
      stationNames = stationMtbfArray.map((item) => item[0]);
      values = stationMtbfArray.map((item) => item[1]);
    }
  } else {
    // 显示所有厂商的所有电站数据
    const allStationMaps = mtbfData.reduce((acc, item) => {
      if (item.stationMtbfMap) {
        return { ...acc, ...item.stationMtbfMap };
      }
      return acc;
    }, {});
    const allStationArray = Object.entries(allStationMaps);
    // 按MTBF值从大到小排列
    allStationArray.sort((a, b) => b[1] - a[1]);
    stationNames = allStationArray.map((item) => item[0]);
    values = allStationArray.map((item) => item[1]);
  }

  // 如果没有数据，显示暂无数据
  if (stationNames.length === 0 || values.length === 0) {
    const option = {
      title: {
        text: "暂无数据",
        left: "center",
        top: "center",
        textStyle: {
          color: "#94a3b8",
          fontSize: 14,
        },
      },
      backgroundColor: "transparent",
    };
    rightChart2.setOption(option);
    return;
  }

  const option = {
    tooltip: {
      trigger: "axis",
      axisPointer: {
        type: "shadow",
      },
      backgroundColor: "rgba(0,0,0,0.7)",
      borderColor: "#334155",
      textStyle: {
        color: "#e2e8f0",
      },
    },
    grid: {
      left: "3%",
      right: "4%",
      bottom: "0",
      top: "3%",
      containLabel: true,
    },
    xAxis: {
      type: "category",
      data: stationNames,
      axisLine: {
        lineStyle: {
          color: "#475569",
        },
      },
      axisTick: {
        show: false,
        alignWithLabel: true,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
        interval: 0,
        rotate: 45,
      },
    },
    yAxis: {
      type: "value",
      axisLine: {
        show: false,
      },
      splitNumber: 4,
      axisTick: {
        show: false,
      },
      axisLabel: {
        color: "#94a3b8",
        fontSize: 12,
      },
      splitLine: {
        show: false,
        lineStyle: {
          color: "#334155",
          type: "dashed",
        },
      },
    },
    series: [
      {
        type: "bar",
        barWidth: 16,
        data: values,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: "rgb(17, 168, 219)" },
            { offset: 1, color: "rgb(56, 229, 165)" },
          ]),
          borderRadius: [8, 8, 0, 0],
        },
        showBackground: true,
        backgroundStyle: {
          color: "rgba(51, 65, 85, 0.4)",
          borderRadius: [8, 8, 0, 0],
        },
      },
    ],
  };

  rightChart2.setOption(option);
};

const handleReset = async () => {
  dateRange.value = getDefaultDateRange();
  selectedBarIndex1.value = -1;
  selectedBarIndex2.value = -1;
  leftChartRefTitle1.value = "所有厂商";
  leftChartRefTitle2.value = "所有厂商";
  await outageDashboardData();
};

const handleResize = () => {
  leftChart1 && leftChart1.resize();
  rightChart1 && rightChart1.resize();
  leftChart2 && leftChart2.resize();
  rightChart2 && rightChart2.resize();
};
const getMTTR = async () => {
  const params = {
    planShutdown: 0, // 供应链评价这里直接传0
    dashboardStartDate: dateRange.value[0],
    dashboardEndDate: dateRange.value[1],
    dashboardType: "6", // 6: MTTR  8: MTBF
  };
  loading1.value = true;
  const res = await $api.faultDealDashboard(6, params);
  loading1.value = false;
  if (res?.code === 0 && Object.keys(res.data).length > 0) {
    mttrChartData.value = res.data; // 存储到MTTR独立数据
  } else {
    mttrChartData.value = {};
  }
  initLeftChart1();
  initRightChart1();
};
const getMTBF = async () => {
  const params = {
    planShutdown: 0, // 供应链评价这里直接传0
    dashboardStartDate: dateRange.value[0],
    dashboardEndDate: dateRange.value[1],
    dashboardType: "8", // 6: MTTR  8: MTBF
  };
  loading2.value = true;
  const res = await $api.faultDealDashboard(8, params);
  loading2.value = false;
  if (res?.code === 0 && Object.keys(res.data).length > 0) {
    mtbfChartData.value = res.data; // 存储到MTBF独立数据
  } else {
    mtbfChartData.value = {};
  }
  initLeftChart2();
  initRightChart2();
};
const outageDashboardData = async () => {
  getMTTR();
  getMTBF();
};
onMounted(async () => {
  await outageDashboardData();
  window.addEventListener("resize", handleResize);
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
  leftChart1 && leftChart1.dispose();
  rightChart1 && rightChart1.dispose();
  leftChart2 && leftChart2.dispose();
  rightChart2 && rightChart2.dispose();
});
</script>

<style scoped lang="less">
.SupplierResponse {
  flex: 1;
  min-width: 0;
  height: 650px;
  width: 100%;
  padding: 0 12px;
  background: #141414;
  border-radius: 4px;
  border: 1px solid #334155;
  color: #e2e8f0;
  display: flex;
  flex-direction: column;
  overflow: hidden;

  .titleBar {
    flex-shrink: 0;
  }

  .title {
    font-size: 16px;
    font-weight: bold;
    padding: 15px 0;
    border-bottom: 1px solid #334155;
    color: #e2e8f0;
    position: relative;
    flex-shrink: 0;

    .dateRange {
      position: absolute;
      right: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .timeSelect {
    padding: 0 8px;
    width: 140px;
  }

  .content {
    height: 300px;
    display: flex;
    padding-top: 15px;
    overflow: hidden;
    margin-bottom: 10px;

    .leftChart,
    .rightChart {
      position: relative;
      height: 100%;

      .chartTitle {
        text-align: center;
        font-size: 14px;
        font-weight: bold;
        color: #e2e8f0;
        margin-bottom: 10px;
      }

      .chartContainer {
        width: 100%;
        height: 200px;
      }
      .chartContainer1 {
        height: 240px;
      }
    }

    :deep(.ant-spin-container) {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    :deep(.ant-spin-spinning) {
      position: relative;
      display: flex;
      align-items: center;
      justify-content: center;
      height: 200px;
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

    .leftChart {
      flex: 1;
      margin-right: 10px;
    }

    .rightChart {
      flex: 2;
    }
  }
  .tips {
    text-align: left;
    font-size: 12px;
    color: #94a3b8;
    margin-top: 5px;
    line-height: 1.5;
    padding: 0 10px;
    opacity: 0.8;
  }
}
</style>
